# == Schema Information
#
# Table name: carts
#
#  id         :integer          not null, primary key
#  user_id    :integer
#  user_uuid  :string
#  product_id :integer
#  amount     :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  channel_id :integer
#

class Cart < ApplicationRecord

  validates :user_uuid, presence: true
  validates :product_id, presence: true
  validates :amount, presence: true
  validates :channel_id, presence: true

  belongs_to :product

  scope :by_user_uuid, -> (user_uuid) { where(user_uuid: user_uuid) }

  def self.create_or_update! options = {}
    product = Product.find(options[:product_id])
    channel_id = product.channel_id
    cond = {
      user_uuid: options[:user_uuid],
      product_id: options[:product_id],
      channel_id: channel_id
    }

    record = where(cond).first
    if record
      record.update_attributes!(options.merge(amount: record.amount + options[:amount]))
    else
      record = create!(cond.merge(amount: options[:amount]))
    end

    record
  end

end
